<template>
  <a-select
    :getPopupContainer="getPopupContainer"
    :placeholder="placeholder"
    :disabled="disabled"
    :value="getValueSting"
    @change="handleInput"
  >
    <a-select-option :value="undefined">请选择</a-select-option>
    <a-select-option v-for="(item, key) in dictOptions" :key="key" :value="item.value">
      <slot :item="item">
        <span style="display: inline-block;width: 100%" :title="item.text || item.label">
          {{ item.text || item.label }}
        </span>
      </slot>
    </a-select-option>
  </a-select>
</template>

<script>
import { ajaxGetDictItems, getDictItemsFromCache } from '@api/api'
import { getAction } from '@api/manage'

export default {
  name: 'HfDictSelect',
  props: {
    dataUrl: String,
    placeholder: String,
    disabled: Boolean,
    value: [String, Number],
    type: String,
    getPopupContainer: {
      type: Function,
      default: node => node.parentNode
    }
  },
  data() {
    return {
      dictOptions: [],
      tagType: ''
    }
  },
  watch: {
    dataUrl: {
      immediate: true,
      handler() {
        this.initDictData()
      }
    }
  },
  created() {
    // console.log(this.dictCode);
    if (!this.type || this.type === 'list') {
      this.tagType = 'select'
    } else {
      this.tagType = this.type
    }
    //获取字典数据
    // this.initDictData();
  },
  computed: {
    getValueSting() {
      // update-begin author:wangshuai date:20200601 for: 不显示placeholder的文字 ------
      // 当有null或“” placeholder不显示
      return this.value != null ? this.value.toString() : undefined
      // update-end author:wangshuai date:20200601 for: 不显示placeholder的文字 ------
    }
  },
  methods: {
    initDictData() {
      //根据url, 初始化字典数组
      getAction(this.dataUrl).then(res => {
        if (res.success) {
          this.dictOptions = res.result || res.reult.records
        }
      })
    },
    handleInput(e = '') {
      let val
      if (Object.keys(e).includes('target')) {
        val = e.target.value
      } else {
        val = e
      }
      console.log(val)
      this.$emit('change', val)
      //LOWCOD-2146 【菜单】数据规则，选择自定义SQL 规则值无法输入空格
      this.$emit('input', val)
    },
    setCurrentDictOptions(dictOptions) {
      this.dictOptions = dictOptions
    },
    getCurrentDictOptions() {
      return this.dictOptions
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style scoped></style>
